"use strict"
var keystone = require('keystone');
var User = keystone.list("User");

var passport = require('passport')
    , LocalStrategy = require('../libs/passport-local/index').Strategy

exports.init = function (auth_provider, app_id, scope) {

    if (auth_provider === "local" && scope === "local_user") {
        passport.use(new LocalStrategy({
            usernameField: 'phone',
            passReqToCallback: true,
            session: true
        },

            function (req, username, password, verified) {
                User.model.findOne({
                    phone: username
                }, (err, user) => {
                    if (err)
                        return verified(err);
                    if (user) {

                        user._.password.compare(password, function (err, isMatch) {
                            if (!err && isMatch) {
                                user.last_access = new Date();
                                user.save((err, user) => {
                                    if (err)
                                        return verified(err);
                                    return verified(null, user);
                                });
                            } else {
                                return verified(null, false, 'err_password');
                            }
                        });

                    } else {

                        return verified(null, false, 'err_phone');


                    }
                });
            }
        ));
        return;
    }

};

